<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    append-to-body
    :close-on-click-modal="false"
    @close="closeDialog()"
    :visible="visible"
    width="600px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <el-form-item label="活动名称" prop="bannerName">
        <el-input
          v-model="dataForm.bannerName"
          placeholder="请输入活动名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="活动主图" prop="bannerImage">
         <ImageUploadSingle v-model="dataForm.bannerImage"></ImageUploadSingle>
      </el-form-item>
      <el-form-item label="跳转类型:" prop="navType">
        <el-radio-group v-model="dataForm.navType" @change="handleNavTypeChange">
          <el-radio label="1" border>商品</el-radio>
          <el-radio label="2" border>权益包</el-radio>
          <el-radio label="9" border>网页</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="跳转网址:" prop="navUrl" v-if="dataForm.navType === '9'">
        <el-input
          v-model="dataForm.navUrl"
          placeholder="请输入跳转网址"
        ></el-input>
      </el-form-item>
      <template v-else-if="dataForm.navType === '1'">
        <el-form-item label="商品信息:" prop="spuId" >
          <el-select
            v-model="dataForm.spuId"
            filterable
            placeholder="请选择商品信息"
            clearable
            size="small"
            class="margin-left-xs"
            style="width:100%"
            @change="handleSpuChange"
          >
            <el-option
              v-for="dict in goodsSpuList"
              :key="dict.id"
              :label="dict.spuTitle"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品Sku:" prop="skuId">
          <el-select
            v-model="dataForm.skuId"
            filterable
            placeholder="请选择商品Sku"
            clearable
            size="small"
            class="margin-left-xs"
            style="width:100%"
          >
            <el-option
              v-for="dict in goodsSkuList"
              :key="dict.id"
              :label="dict.skuShortName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </template>
      <template v-else-if="dataForm.navType === '2'">
        <el-form-item label="权益包:" prop="spuId">
          <el-select
            v-model="dataForm.spuId"
            filterable
            placeholder="请选择权益包"
            clearable
            size="small"
            class="margin-left-xs"
            style="width:100%"
          >
            <el-option
              v-for="dict in shopEquityList"
              :key="dict.id"
              :label="dict.equityName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      </template>
      
      <el-form-item label="上架状态:" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio label="1" border>上架</el-radio>
          <el-radio label="0" border>下架</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="排序:" prop="sort">
        <el-input-number
          v-model="dataForm.sort"
          controls-position="right"
          :min="0"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" :rows="4" v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { getObj, addObj, putObj } from "@/api/shop/config/banner";
import ImageUploadSingle from '@/components/imageUploadSingle';
import {getGoodsSpuList} from '@/api/shop/goods/spu';
import {getGoodsSkuBySpuId} from '@/api/shop/goods/sku';
import {getShopEquityList} from '@/api/shop_user/equity'

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      canSubmit: false,
      dataForm: {
        spuId:'',
        skuId:'',
        navType:'1',
        bannerImage:null,
        status:'1'
      },
      dataRule: {
        bannerName: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        bannerImage: [
          { required: true, message: "活动图片不能为空", trigger: "blur" },
        ],
        navType: [
          { required: true, message: "跳转类型不能为空", trigger: "blur" },
        ],
        navUrl: [
          { required: true, message: "跳转类型不能为空", trigger: "blur" },
        ],
        spuId: [
          { required: true, message: "商品信息不能为空", trigger: "blur" },
        ],
        skuId: [
          { required: true, message: "商品Sku不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "上架状态不能为空", trigger: "blur" },
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
      },
      goodsSpuList:[],
      goodsSkuList:[],
      shopEquityList:[],
    };
  },
  components: {
    ImageUploadSingle,
  },
  watch:{

    /**
     * 商品Spu发生变化
     */
    // 'dataForm.spuId':function(val){
    //   this.dataForm.skuId = ''
    //   this.getGoodsSkuBySpuId(val)
    // }
  },
  methods: {
    init(id) {
      this.canSubmit = true;
      // 商品列表
      this.getGoodsSpuList()
      // 权益包列表
      this.getShopEquityList()
      if(id){
        getObj(id).then((response) => {
          let data = response.data.data;
          if(data.bannerImage){
            let arr = JSON.parse(data.bannerImage)
            if(arr.length > 0){
              data.bannerImage = arr[0]
            }
          }
          this.dataForm = data
          this.getGoodsSkuBySpuId(this.dataForm.spuId)
        });
      }
    },

    handleSpuChange(val){
      console.log(val)
      this.dataForm.skuId = ''
      this.getGoodsSkuBySpuId(val)
    },

    /**
     * 获取所有的商品spu
     */
    getGoodsSpuList(){
      getGoodsSpuList().then(res=>{
        this.goodsSpuList = res.data.data
      })
    },

    /**
     * 根据spuId获取sku列表
     */
    getGoodsSkuBySpuId(spuId){
      getGoodsSkuBySpuId({spuId}).then(res=>{
        this.goodsSkuList = res.data.data
      })
    },

    /**
     * 获取权益包列表
     */
    getShopEquityList(){
      getShopEquityList().then(res=>{
        this.shopEquityList = res.data.data
      })
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          let requestData = JSON.parse(JSON.stringify(this.dataForm))
          requestData.bannerImage = requestData.bannerImage.materialId
          if (requestData.id) {
            putObj(requestData)
              .then((data) => {
                this.$notify.success("修改成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(requestData)
              .then((data) => {
                this.$notify.success("添加成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          }
        }
      });
    },
    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },

    /**
     * 切换类型
     */
    handleNavTypeChange(){
      this.dataForm.spuId = ''
      this.dataForm.skuId = ''
      this.dataForm.navUrl = ''
      this.$refs["dataForm"].clearValidate()
    }
  },
};
</script>
